package com.nova.android.tvlauncher.ui.adapter.atv

import android.R.attr.targetId
import android.view.KeyEvent
import android.view.View
import android.view.View.GONE
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.widget.FrameLayout
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.core.view.setPadding
import androidx.leanback.widget.HorizontalGridView
import androidx.leanback.widget.VerticalGridView
import com.nova.android.tvlauncher.AppCache
import com.nova.android.tvlauncher.R
import com.nova.android.tvlauncher.bean.atv_bean.HomeParentDto
import com.nova.android.tvlauncher.databinding.ItemAppParentAtvBinding
import com.nova.android.tvlauncher.databinding.ItemHomeFooterAtvBinding
import com.nova.android.tvlauncher.ui.view.atv.HomeLeftMenuAtvView
import com.hjq.shape.layout.ShapeConstraintLayout
import com.nova.android.tvlauncher.bean.atv_bean.Movy
import com.shudong.lib_base.ext.appContext
import com_github_lib_base.ext.clickNoRepeat
import com_github_lib_base.ext.dimenValue
import com_github_lib_base.ext.rv.BindAdapter
import com_github_lib_base.ext.rv.models
import com_github_lib_base.ext.rv.removeModelAt
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.Collections
import kotlin.collections.forEachIndexed

object HomeListAtvAdapter {
    fun bindData(
        binding: BindAdapter,
        rvHome: VerticalGridView
    ){
       binding.apply {
           if(data is String){
               //添加footer
               val itemParentBinding = getBinding<ItemHomeFooterAtvBinding>()
               HomeListFooterAtvAdapter.bindData(itemParentBinding)
           }else{
               val itemParentBinding = getBinding<ItemAppParentAtvBinding>()
               val item = getModel<HomeParentDto>()

               itemParentBinding.tvTitle.text = item.title

               when{
                   item.apps!=null->{
                       HomeListFavoriteAppAtvAdapter.bindData(itemParentBinding,item.apps!!)
                   }
                   item.recommondInfoDtoList!=null ->{
                       HomeListChannelDataAtvAdapter.bindData(itemParentBinding,binding,rvHome)
                   }
               }
               if (item.isLeftMenuShowed){
                   if(!HomeListChannelDataAtvAdapter.isCanRemove){
                       itemParentBinding.leftMenu.tvRemove().visibility = View.GONE
                   }else{
                       itemParentBinding.leftMenu.tvRemove().visibility = INVISIBLE
                   }

                   itemParentBinding.leftMenu.tvMove().visibility = INVISIBLE
                   itemParentBinding.leftMenu.leftArrow().isVisible = false
               }else{
                   itemParentBinding.leftMenu.tvRemove().isVisible = false
                   itemParentBinding.leftMenu.tvMove().isVisible = false
                   if(item.isShowLestArrow)itemParentBinding.leftMenu.leftArrow().visibility = VISIBLE
                   else itemParentBinding.leftMenu.leftArrow().visibility = INVISIBLE
               }
               itemParentBinding.root.onKeyEvent(rvHome,itemParentBinding,binding)
               itemParentBinding.leftMenu.tvRemove().onClickEvent(rvHome,itemParentBinding,binding)
           }
       }


    }

    fun ShapeConstraintLayout.onKeyEvent(
        rvHome: VerticalGridView,
        itemParentBinding: ItemAppParentAtvBinding,
        binding: BindAdapter,
    ) {
        this.setOnKeyListener { _, keyCode, event ->
            if (event.action == KeyEvent.ACTION_DOWN) {
                when (keyCode) {
                    KeyEvent.KEYCODE_DPAD_UP -> {
                        if (binding.modelPosition <= 1) {
                            updateIconForPosition(binding.modelPosition,itemParentBinding,binding.models) // 确保图标正确
                            return@setOnKeyListener true
                        }
                        // 向上替换（与上一个 Item 交换）
                        val newPosition = binding.modelPosition - 1
                        binding.swapItems(binding.modelPosition, newPosition)
                        updateIconForPosition(binding.modelPosition,itemParentBinding,binding.models) // 更新图标
                        return@setOnKeyListener true
                    }
                    KeyEvent.KEYCODE_DPAD_DOWN -> {

                        if (binding.modelPosition >=  rvHome.models.size - 2) {
                            updateIconForPosition(binding.modelPosition,itemParentBinding,binding.models) // 确保图标正确
                            return@setOnKeyListener true
                        }
                        // 向下替换（与下一个 Item 交换）
                        binding.swapItems(binding.modelPosition, binding.modelPosition + 1)
                        updateIconForPosition(binding.modelPosition,itemParentBinding,binding.models) // 更新图标
                        return@setOnKeyListener true
                    }
                    KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_DPAD_CENTER -> {


                        binding.models.forEachIndexed { index,dto->
                            if(dto is HomeParentDto){
                                dto.isLeftMenuShowed = false
                                if(index!=binding.modelPosition){

                                       /* val childView = rvHome.getChildAt(index)
                                        val leftMenu = childView?.findViewById<HomeLeftMenuAtvView>(R.id.left_menu)
                                        val rvHori = childView?.findViewById<HorizontalGridView>(R.id.rv_horizontal)
                                        rvHori?.scrollToPosition(0)
                                        leftMenu?.tvRemove()?.visibility = GONE
                                        leftMenu?.tvMove()?.visibility = GONE
                                        leftMenu?.leftArrow()?.visibility = INVISIBLE

                                        binding.adapter.notifyItemChanged(index)*/

                                    /**/

                                }else{
                                    itemParentBinding.root.isFocusable = false
                                    itemParentBinding.root.isFocusableInTouchMode = false
                                    itemParentBinding.root.setPadding(0)

                                    itemParentBinding.leftMenu.tvRemove().isVisible = false
                                    itemParentBinding.leftMenu.tvMove().isVisible = false
                                    itemParentBinding.leftMenu.leftArrow().isVisible = true
                                    itemParentBinding.rvHorizontal.requestFocus()
                                }
                            }

                        }
                        rvHome.post {
                            rvHome.adapter?.notifyDataSetChanged()
                        }
                        rvHome.requestLayout()

                        return@setOnKeyListener true

                    }
                }
            }
            false
        }
    }

    fun FrameLayout.onClickEvent(
        rvHome: VerticalGridView,
        itemParentBinding: ItemAppParentAtvBinding,
        binding: BindAdapter,
    ) {
        this.clickNoRepeat {
            val dto  = binding.data as HomeParentDto
            updateWithCopy(dto.packageName,dto.channelId,false)

            rvHome.removeModelAt(binding.modelPosition)
            binding.models.forEachIndexed { index,dto->
                if(dto is HomeParentDto){
                    dto.isLeftMenuShowed = false
                   /* if(index!=binding.modelPosition){
                        binding.adapter.notifyItemChanged(index)
                    }*/
                }

            }
            rvHome.post {
                rvHome.adapter?.notifyDataSetChanged()
            }
            rvHome.requestLayout()



        }
        this.setOnKeyListener { _, keyCode, event ->
            if (event.action == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT||keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
                    false // 允许右键事件继续向下传递（即让它生效）
                }else if(keyCode== KeyEvent.KEYCODE_BACK){
                    binding.models.forEachIndexed { index, dto ->
                        if (dto is HomeParentDto) {
                            dto.isLeftMenuShowed = false
                            dto.isShowLestArrow = false
                            if (index != binding.modelPosition) {

                                rvHome.post { rvHome.adapter?.notifyItemChanged(index) }


                            } else {
                                dto.isShowLestArrow = true
                                itemParentBinding.leftMenu.tvMove().isVisible = false
                                itemParentBinding.leftMenu.tvRemove().isVisible = false
                                itemParentBinding.leftMenu.leftArrow().isVisible = true
                                //itemParentBinding.rvHorizontal.requestFocus()

                            }
                        }

                    }
                    true
                } else {
                    true // 拦截所有其他按键（即不让它们生效）
                }
            } else {
                false // 非 DOWN 事件默认不处理
            }
        }


    }

    // 更新当前 Item 的图标
    private fun updateIconForPosition(
        position: Int,
        itemParentBinding: ItemAppParentAtvBinding,
        models: List<Any>
    ) {
        val iconView = itemParentBinding.leftMenu.tvMove()
        val iconRes = when {
            position == 1 -> R.drawable.icon_move_down_normal // 索引 1 显示向下箭头
            position == models.size - 1 -> R.drawable.icon_move_updown_normal // 最后一个显示向上箭头
            else -> R.drawable.icon_move_up_normal // 其他显示上下箭头
        }
        iconView.setImageNormalSrc(ContextCompat.getDrawable(appContext, iconRes))
    }


    fun BindAdapter.swapItems(fromPosition: Int, toPosition: Int) {
        Collections.swap(this.models, fromPosition, toPosition)
        this.dslAdapter.notifyItemMoved(fromPosition, toPosition)
    }

    fun updateWithCopy(packageName: String, targetId: Long, isShow: Boolean) {
        AppCache.channelList = AppCache.channelList.map { channel ->
            if (channel.packageName == packageName) {
                channel.copy(
                    channelDataList = channel.channelDataList.map { data ->
                        if (data.channelId == targetId) data.copy(isShowChannelData = isShow)
                        else data
                    }.toMutableList()
                )
            } else channel
        }.toMutableList()
    }
}